package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.config.MyRedissonConfig;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class indexController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @ResponseBody
    @GetMapping("hello")
    public String testReadAndWriteLock() {
        String s = "";
        RReadWriteLock lock = redissonClient.getReadWriteLock("readWrite");
        RLock rLock = lock.readLock();
        try {
            rLock.lock();
            System.out.println("上写锁");
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("解写锁");
        }
        return s;
    }

    @ResponseBody
    @GetMapping("hello1")
    public String testReadAndWriteLock1() {
        String s = "";
        RReadWriteLock lock = redissonClient.getReadWriteLock("readWrite");
        RLock rLock = lock.writeLock();
        try {
            rLock.lock();
            System.out.println("上读锁");
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("解读锁");

        }
        return s;
    }

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        //TODO 1. 查询所有的分类
        List<CategoryEntity> categoryEntitys = categoryService.listLevel1Categorys();
        model.addAttribute("categorys", categoryEntitys);
        return "index";
    }

    ;

    //index/json/catalog.json
    @ResponseBody
    @GetMapping("/index/json/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        Map<String, List<Catelog2Vo>> catelogJson = categoryService.getCatelogFromRedis();
        return catelogJson;
    }

   /* @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }*/
}
